//TIP 要<b>运行</b>代码，请按 <shortcut actionId="Run"/> 或
// 点击装订区域中的 <icon src="AllIcons.Actions.Execute"/> 图标。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;



public class FileZipper {
    public static void main(String[] args) {
        String directoryPath = "txt"; // 源文件所在的目录路径
        String zipDirectoryPath = "ZIP"; // ZIP文件存放的目录路径

        long startTime = System.currentTimeMillis(); // 记录开始时间

        try {
            Files.createDirectories(Path.of(zipDirectoryPath)); // 确保ZIP目录存在，如果不存在则创建
            Files.walk(Path.of(directoryPath))
                    .filter(Files::isRegularFile)
                    .parallel() // 启用并行流
                    .forEach(path -> compressFile(path, Path.of(zipDirectoryPath)));
        } catch (IOException e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis(); // 记录结束时间
        long duration = endTime - startTime; // 计算执行时间

        System.out.println("Total execution time: " + duration + "ms");
    }

    private static void compressFile(Path fileToCompress, Path zipDirectory) {
        Path zipFilePath = zipDirectory.resolve(fileToCompress.getFileName() + ".zip");
        try (FileOutputStream fos = new FileOutputStream(zipFilePath.toFile());
             ZipOutputStream zos = new ZipOutputStream(fos);
             FileInputStream fis = new FileInputStream(fileToCompress.toFile())) {
            ZipEntry zipEntry = new ZipEntry(fileToCompress.getFileName().toString());
            zos.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }
            zos.closeEntry();
            // 在并行执行时，此输出可能会导致控制台输出混乱，因此在实际应用中可能需要去掉
            System.out.println("Successfully compressed: " + fileToCompress);
        } catch (IOException e) {
            System.err.println("Error compressing file: " + fileToCompress);
            e.printStackTrace();
        }
    }
}